# -*- coding: utf-8 -*-
import json
import time
import cv2
import requests
import base64
from PIL import Image
import io


def save_base64_image(base64_image, output_path):
    # 解码 Base64 图像数据
    image_bytes = base64.b64decode(base64_image)

    # 将字节数据转为 BytesIO 对象
    image_stream = io.BytesIO(image_bytes)

    # 打开图像文件并保存到指定路径
    with Image.open(image_stream) as image:
        image.save(output_path)


def cv2_to_base64(image):
    base64_str = cv2.imencode('.jpg', image)[1].tobytes()  # tostring()
    base64_str = base64.b64encode(base64_str)
    return str(base64_str, "utf-8")


def ocr(img):
    params = json.dumps({"img": img})
    headers = {
        'Content-Type': 'application/json'
    }
    request_url = "https://u12453-8224-18ad9912.westb.seetacloud.com:8443/predict/rv_watermark"
    response = requests.post(request_url, headers=headers, data=params)
    if response:
        data = response.json()
        return data


if __name__ == "__main__":
    import glob

    # imglist = glob.glob(r'/home/zhangjie/data/imgs/val/img_watermark/*.jpg')
    # for img in imglist:
    #     s = time.time()
    img = cv2.imread(r'E:\PythonMyCode\cv_about\watermark-cleaner-demo\utils\imgs\origin\YK2390_2.jpg')
    img = cv2_to_base64(img)
    data = ocr(img)
    img_base64 = data['results']
    # print(time.time()-s)
    save_base64_image(img_base64, '123.png')
    # exit()
